using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Core;
using FreeLancer.HRB.Core.Web.Controls;

namespace FreeLancer.HRB.WebApp
{
  public partial class Page : WebBasePage
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        if (Request.RawUrl.Contains("?id=") && Request.QueryString["id"].Length == 36)
        {
          Guid id = new Guid(Request.QueryString["id"]);
          FreeLancer.HRB.Domains.Page pageData = GlobalCache.PageServiceInstance.
            GetByPageIdLanguageId(id, _languageId);

          FreeLancer.HRB.Core.Page page = null;
          if (pageData != null)
          {
            page = new FreeLancer.HRB.Core.Page(pageData);
          }
          
          if (page != null)
          {
            Response.Clear();
            Response.StatusCode = 301;
            Response.AppendHeader("location", page.RelativeLink.ToString());
            Response.End();
          }
          else
          {
            Response.Redirect(Utils.RelativeWebRoot + "Error404.aspx", true);
          }
        }
      }

      if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
      {
        InitializePageData();
      }
      else
      {
        Response.Redirect(Utils.RelativeWebRoot + "Error404.aspx", true);
      }
    }

    private void InitializePageData()
    {
      Guid id = new Guid(Request.QueryString["id"]);
      FreeLancer.HRB.Domains.Page pageData = GlobalCache.PageServiceInstance.
        GetByPageIdLanguageId(id, _languageId);

      anchorPageName.InnerText = pageData.Title;
      spanDateTime.InnerText = pageData.DateModified.ToString();
      divContent.InnerHtml = pageData.PageContent;

      if (!string.IsNullOrEmpty(pageData.AttachedPath))
      {
        divAttachedFile.Visible = true;
        linkAttachedFile.Text = pageData.AttachedPath.Substring(pageData.AttachedPath.IndexOf('_') + 1);
        linkAttachedFile.NavigateUrl =
          Utils.RelativeWebRoot + "Files/PageFiles/" + pageData.AttachedPath;
      }
      else
      {
        divAttachedFile.Visible = false;
      }

      Title = pageData.Title + " - HRB";

      PreparePrintAnchor(id.ToString());
    }

    private void PreparePrintAnchor(string pageId)
    {
      anchorPrintPreview.HRef = "javascript:poptastic('" +
        Utils.AbsoluteWebRoot + "PagePrintPreview.aspx?id=" +
        pageId + "')";

      anchorPrint.HRef = "javascript:poptastic('" +
        Utils.AbsoluteWebRoot + "PagePrintPreview.aspx?id=" +
        pageId + "&print=1')";
    }
  }
}
